/*
 * @Author: 李环玉 834654733@qq.com
 * @Date: 2023-11-24 17:30:32
 * @LastEditors: 李环玉 834654733@qq.com
 * @LastEditTime: 2023-12-01 17:23:36
 * @FilePath: \koa-server\src\middleware\user.middleware.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

const bcrypt = require('bcryptjs')

const { success,error } = require('../utils/response')
const { getUserInfo } = require('../service/user.service')

const userValidator = async (ctx,next) => {
  const { userName,passWord } = ctx.request.body

  if(!userName || !passWord){
    error(ctx,null,'用户名和密码不能为空',400)
    return
  }
  await next()
}
const VerifyDuplicate = async (ctx,next) => {
  const params = ctx.request.body
  try{
    const res = await getUserInfo(params)
    if(res){
      error(ctx,null,'该用户已经存在',501)
      return
    }
  } catch(err){
    error(ctx,null,err,502)
    return
  }
  await next()
}
const cryptPassWord = async (ctx,next) => {
  const { passWord } = ctx.request.body
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(passWord, salt); 
  ctx.request.body.passWord = hash
  await next()
}
const verifyLogin = async (ctx,next) => {
 //1、用户是否存在
 const { userName,passWord } = ctx.request.body
 try{
  const res = await getUserInfo({userName})
  if(!res){
    error(ctx,null,'您还未注册，请先注册',501)
    return
  }
  if(!bcrypt.compareSync(passWord,res.passWord)){
    error(ctx,null,'密码输入不正确',501)
    return
  }
 } catch(err){
    error(ctx,null,err,502)
    return
 }
 await next()
}
module.exports = {
  userValidator,
  VerifyDuplicate,
  cryptPassWord,
  verifyLogin
}
